#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "tcp.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>

#define MAX_FILE_SIZE   (64 * 1024)

// ref: https://blog.csdn.net/baixingyubxy/article/details/125964986

typedef struct {
    int fd;
} session_t;

char *get_resource(char *buf)
{
    static char res[128] = {0};
    return "/index.html";
}

static int http_send_status()
{
    return 0;
}

static char *get_null(char *text)
{
    while (*text) {
        text++;
    }
    return text;
}

int http_send_file(int cfd, char *file)
{
    char head[1024] = {0};
    char data[1024] = {0};

    int fd = open(file, O_RDONLY);
    if (fd < 0) {
        printf("open failed: %s\n", file);
        http_send_status();
        return -1;
    }

    int size = lseek(fd,0,SEEK_END);
    lseek(fd,0,SEEK_SET);

    sprintf(head,
            "HTTP/1.1 200 OK\r\n" \
            "Server: mini http\r\n" \
            "Content-Length: %d\r\n" \
            "\r\n",
            size);
    send(cfd, head, strlen(head), 0);

    int len = 0;
    while ((len = read(fd, data, MAX_FILE_SIZE)) > 0) {
        send(cfd, data, len, 0);
    }

    close(fd);
}

int on_connected(int fd, void **pdata)
{
    session_t *s = (session_t *)malloc(sizeof(session_t));
    if (s == NULL) {
        printf("malloc: failed!\n");
        return -1;
    }
    s->fd = fd;
    (*pdata) = (void *)s;
    return 0;
}

int on_readable(int *ret_fd, void *data)
{
    session_t *s = (session_t *)data;
    int fd = s->fd;

    char buf[1024] = {0};

    int ret = recv(fd, buf, sizeof(buf), 0);
    if (ret <= 0) {
        printf("[disconnected!]\n");
        free(data);
        *ret_fd = fd;
        return -1;
    }
    printf("%s(%d)\n", buf, ret);
    //get_resource(NULL);
    http_send_file(fd, "index.html");
    // send(fd, buf, ret, 0);
    return 0;
}


int main()
{
    launch_server(8086, on_connected, on_readable);
}
